package cn.fz.ssedemo.controller;

import cn.fz.ssedemo.constant.CacheConstants;
import cn.fz.ssedemo.domain.vo.ResultVO;
import cn.fz.ssedemo.utils.Base64;
import cn.fz.ssedemo.utils.IdUtils;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.RandomUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.img.ImgUtil.toBufferedImage;

@RestController
public class CommonController {
    @GetMapping("/captchaImage")
    public ResultVO<Map<String, Object>> getCode(HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;


        // String capText = captchaProducerMath.createText();
        String capText = "8-5=?@3";
        String capStr = capText.substring(0, capText.lastIndexOf("@"));
        String code = capText.substring(capText.lastIndexOf("@") + 1);
// 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            BufferedImage image = createImage(capStr);
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return ResultVO.success(map);
    }

    private BufferedImage createImage(String capStr) {
        //定义图形验证码的长、宽、验证码位数、干扰圈圈数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 50,4,0);
        //设置背景颜色
        circleCaptcha.setBackground(new Color(249, 251, 220));
        //生成四位验证码
        // String code = RandomUtil.randomNumbers(4);
        Image image = circleCaptcha.createImage(capStr);
        return toBufferedImage(image);
    }
}
